//
//  MSSettingVC.m
//  MS
//
//  Created by Yuan on 13-4-11.
//  Copyright (c) 2013年 He Yuan. All rights reserved.
//

#import "MSSettingVC.h"
#import "UIImageView+WebCache.h"
#import <QuartzCore/QuartzCore.h>
#import "MSAppDelegate.h"
#import "MSRemindSettingVC.h"
#import "MSFeedBackVC.h"
#import "MSEditPasswordVC.h"
#import "MSRemindSettingVC.h"
#import "MSEveryDayRecommendVC.h"
#import "MSEditUserInfo.h"

@interface MSSettingVC ()
{
    UIScrollView *tScrollView;
    
    UIButton *editInfoButton;
    
    UIView *actionView;
    
    UIImageView *socialView;
    
    UIButton *goAppstore;
    
    NSString *updateAppUrl;
}
@end

@implementation MSSettingVC

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)loadView
{
    [super loadView];
    
    tScrollView = [[UIScrollView alloc]initWithFrame:self.view.bounds];
    tScrollView.backgroundColor = [UIColor clearColor];
    tScrollView.contentSize = CGSizeMake(0, self.view.frame.size.height*1.2);
    [self.view addSubview:tScrollView];
    
    UIImage *editImageBg =[UIImage imageNamed:@"me_section_one"];
    editInfoButton = [MSTool createButton:CGRectMake(10, 12, 300, editImageBg.size.height) action:@selector(editUserInfo:) delegate:self];
    [editInfoButton setBackgroundImage:[editImageBg stretchableImageWithLeftCapWidth:editImageBg.size.width/2 topCapHeight:0] forState:UIControlStateNormal];
    [editInfoButton setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    [editInfoButton setTitle:HYLocalizedString(@"个人资料修改") forState:UIControlStateNormal];
    [editInfoButton setTitleEdgeInsets:UIEdgeInsetsMake(0, -160, 0, 0)];
    [tScrollView addSubview:editInfoButton];
    
    UIImageView *avatarImageView = [[UIImageView alloc]initWithFrame:CGRectMake(editInfoButton.frame.size.width - 44, 4, 38, 38)];
    avatarImageView.tag = 1;
    NSString *avatar = [[[MSSetting sharedSetting ]getAccountInfo] objectForKey:@"avatar"];
    if (avatar)
    {
        [avatarImageView setImageWithURL:[NSURL URLWithString:avatar] placeholderImage:[UIImage imageNamed:@"default_img"]];
    }
    avatarImageView.layer.cornerRadius = 4.0;
    avatarImageView.layer.masksToBounds = YES;
    [editInfoButton addSubview:avatarImageView];
    
    [self actionView];
    
    UIImage *socialImage = [UIImage imageNamed:@"me_section_three"];
    socialView = [[UIImageView alloc]initWithFrame:CGRectMake(10, actionView.frame.size.height+actionView.frame.origin.y+12, 300, socialImage.size.height)];
    [socialView setImage:[socialImage stretchableImageWithLeftCapWidth:socialImage.size.width/2 topCapHeight:0]];
    [socialView setUserInteractionEnabled:YES];
    [tScrollView addSubview:socialView];
    
    for (int i = 0 ; i < 2; i++)
    {
        UILabel *lbl = [MSTool createLable:CGRectMake(24,7+i*40, 100, 30)];
        [socialView addSubview:lbl];
        [lbl setTextColor:[UIColor darkGrayColor]];
        [lbl setFont:FONT_MIDDLE_BOLD];
        [lbl setText:i==0?HYLocalizedString(@"新浪微博绑定"):HYLocalizedString(@"腾讯微博绑定")];
    
        UISwitch *uiswitch = [[UISwitch alloc]initWithFrame:CGRectMake(210, lbl.frame.origin.y+2, 50, 30)];
        [socialView addSubview:uiswitch];
    }
    
    CGFloat btnWidth  = 160;
    UIImage *appstoreImage = [UIImage imageNamed:@"me_via"];
    goAppstore = [UIButton buttonWithType:UIButtonTypeCustom];
    [goAppstore setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    [goAppstore.titleLabel setFont:FONT_MIDDLE_BOLD];
    [goAppstore setTitle:HYLocalizedString(@"鼓励一下(=^^=)") forState:UIControlStateNormal];
    [goAppstore setFrame:CGRectMake(self.view.frame.size.width/2-btnWidth/2, socialView.frame.size.height+socialView.frame.origin.y+12, btnWidth,appstoreImage.size.height)];
    [goAppstore setBackgroundImage:[appstoreImage stretchableImageWithLeftCapWidth:appstoreImage.size.width/2 topCapHeight:0] forState:UIControlStateNormal];
    [goAppstore addTarget:self action:@selector(gotoAppStore:) forControlEvents:UIControlEventTouchUpInside];
    [tScrollView addSubview:goAppstore];
    
    btnWidth = 140;
    UIImage *btnImage = [UIImage imageNamed:@"button_bg"];
    UIButton *logout = [MSTool createButton:CGRectMake(self.view.frame.size.width/2-btnWidth/2, goAppstore.frame.size.height+goAppstore.frame.origin.y+20, btnWidth,btnImage.size.height) action:@selector(logOut:) delegate:self];
    [logout setTitle:HYLocalizedString(@"退出登陆") forState:UIControlStateNormal];
    [logout setBackgroundImage:[btnImage stretchableImageWithLeftCapWidth:btnImage.size.width/2 topCapHeight:0] forState:UIControlStateNormal];
    [tScrollView addSubview:logout];
}


-(void)actionView
{
    NSArray *btns = [NSArray arrayWithObjects:
                     HYLocalizedString(@"修改密码"),
                     HYLocalizedString(@"提醒设置"),
                     HYLocalizedString(@"意见反馈"),
                     HYLocalizedString(@"每日推荐"),
                     HYLocalizedString(@"检查更新"),
                     HYLocalizedString(@"清除缓存"),
                     nil];
    UIImage *bgImage = [UIImage imageNamed:@"six_box"];
    actionView = [[UIView alloc]initWithFrame:CGRectMake(10, editInfoButton.frame.size.height+editInfoButton.frame.origin.y+12, bgImage.size.width, bgImage.size.height)];
    [actionView setBackgroundColor:[UIColor colorWithPatternImage:bgImage]];
    for (int i = 0 ;i < 3 ; i++)
    {
        for (int j = 0 ;j < 2; j++)
        {
            NSInteger idx = i*2+j;
            if (idx>=[btns count]) {
                break;
            }
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            [btn setFrame:CGRectMake(j*150, i*bgImage.size.height/3, 150, bgImage.size.height/3)];
            btn.tag = idx+1;
            NSString *btnimage = [NSString stringWithFormat:@"setting_sixbox_%d",btn.tag];
            [btn setImage:[UIImage imageNamed:btnimage] forState:UIControlStateNormal];
            [btn.titleLabel setFont:FONT_MIDDLE_BOLD];
            [btn setImageEdgeInsets:UIEdgeInsetsMake(0, -20, 0, 0)];
            [btn addTarget:self action:@selector(btnsAction:) forControlEvents:UIControlEventTouchUpInside];
            [btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
            [btn setTitle:[btns objectAtIndex:idx] forState:UIControlStateNormal];
            [actionView addSubview:btn];
        }
    }

    [tScrollView addSubview:actionView];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    UIImageView *avatarImageView = (UIImageView *)[editInfoButton viewWithTag:1];
    if (avatarImageView)
    {
        NSString *avatar = [[[MSSetting sharedSetting ]getAccountInfo] objectForKey:@"avatar"];
        if (avatar)
        {
            [avatarImageView setImageWithURL:[NSURL URLWithString:avatar] placeholderImage:[UIImage imageNamed:@"default_img"]];
        }
    }
}

- (void)viewDidLoad
{
    [self setTitle:HYLocalizedString(@"设置") showBackButton:YES];
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)configureViews:(BOOL)animation
{
    [super configureViews:animation];
    
}

//修改个人信息
-(void)editUserInfo:(UIButton *)btn
{
    [self loadViewController:NSStringFromClass([MSEditUserInfo class]) hidesBottomBarWhenPushed:YES];
}

-(void)gotoAppStore:(UIButton *)btn
{
    [[UIApplication sharedApplication]openURL:[NSURL URLWithString:@"http://www.ishowtu.com/cloud_guke.html"]];
}

-(void)btnsAction:(UIButton *)btn
{
    switch (btn.tag) {
        case 1:
            [self editPassword];
            break;
        case 2:
            [self remindSetting];
            break;
        case 3:
            [self feedBack];
            break;
        case 4:
            [self everyDayRecommend];
            break;
        case 5:
            [self checkUpdate];
            break;
        case 6:
            [self clearCache];
            break;
        default:
            break;
    }

}

//修改密码
-(void)editPassword
{
    [self loadViewController:NSStringFromClass([MSEditPasswordVC class]) hidesBottomBarWhenPushed:YES];
}

//提醒设置
-(void)remindSetting
{
    [self loadViewController:NSStringFromClass([MSRemindSettingVC class]) hidesBottomBarWhenPushed:YES];
}

//意见反馈
-(void)feedBack
{
    [self loadViewController:NSStringFromClass([MSFeedBackVC class]) hidesBottomBarWhenPushed:YES];

}

//每日推荐
-(void)everyDayRecommend
{
    [self loadViewController:NSStringFromClass([MSEveryDayRecommendVC class]) hidesBottomBarWhenPushed:YES];
}

//检查更新
-(void)checkUpdate
{
    NSString *vnum = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleVersionKey];
    NSDictionary *p =  [NSDictionary dictionaryWithObjectsAndKeys:
                        vnum,@"version",
                        nil];
    [WebService  getRequestAction:APIGetLastestVersion
                            param:p
                          success:^(NSDictionary *info,NSError *error)
     {
         if (error == nil)
         {
             HYLog(@"%@",info);
             NSDictionary *result = [info objectForKey:@"result"];
             if (result!=nil && [result isKindOfClass:[NSDictionary class]]&& [result count]>0)
             {
                 NSString *isupdate = [result objectForKey:@"isupate"];
                 if ([isupdate integerValue] == 0 )
                 {
                     updateAppUrl = @"";
                     [MSTool showAlertTitle:HYLocalizedString(@"更新提示") message:HYLocalizedString(@"已经是最新版!")];
                 }
                 else
                 {
                     NSString *msg = HYLocalizedString(@"已经有新版#了，赶紧去更新吧，更多好玩有趣的功能等着您~_~");
                     msg = [msg stringByReplacingOccurrencesOfString:@"#" withString:[result objectForKey:@"newversion"]];
                     updateAppUrl = [result objectForKey:@"updateurl"];
                     UIAlertView *alert = [[UIAlertView alloc]initWithTitle:HYLocalizedString(@"更新提示") message:msg delegate:self cancelButtonTitle:HYLocalizedString(@"暂时不更新") otherButtonTitles:HYLocalizedString(@"立即更新"), nil];
                     [alert show];
                 }
             }
         }
         [MSTool showError:error];
     } failure:^(id info ,NSError *error){
         [MSTool showError:error];
     } progress:self.navigationController.view];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        return;
    }
    
    if (updateAppUrl && [updateAppUrl length]>0)
    {
        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:updateAppUrl]];
    }
}


//清除缓存
-(void)clearCache
{
    [MSTool showAlert:HYLocalizedString(@"清除缓存成功!")];
}

-(void)logOut:(UIButton *)btn
{
    [self.navigationController popToRootViewControllerAnimated:YES];
    [[MSAppDelegate sharedAppDelegate] logOut];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
